package com.yeswater.multithread.chapter4;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * author : yeswater
 * date : 2023/10/23
 */

public class Run_4_1_3 {
    public static void main(String[] args) {
        Service service = new Service();
        ThreadA t1 = new ThreadA(service);
        t1.start();
        ThreadA t2 = new ThreadA(service);
        t2.start();
        ThreadA t3 = new ThreadA(service);
        t3.start();
    }

    private static class Service {
        private final Lock lock = new ReentrantLock();
        private final Condition condition = lock.newCondition();

        public void await() {
            try {
                lock.lock();
                System.out.println("A");
                condition.await();
                System.out.println("B");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
                System.out.println("unlock ==>>");
            }
        }
    }

    private static class ThreadA extends Thread {
        private final Service service;

        public ThreadA(Service service) {
            this.service = service;
        }

        @Override
        public void run() {
            service.await();
        }
    }
}
